package com.gykj.tap.service;

import org.springframework.util.StringUtils;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;

public abstract class BaseService {

	public static ModbusFactory modbusFactory;
	
	public ModbusMaster getMaster(String host, int port)
			throws ModbusInitException {
		IpParameters params = new IpParameters();
		params.setHost(StringUtils.isEmpty(host) ? "localhost" : host);
		params.setPort(StringUtils.isEmpty(port) ? 502 : port);

		// modbusFactory.createRtuMaster(wapper); //RTU 协议
		// modbusFactory.createUdpMaster(params);//UDP 协议
		// modbusFactory.createAsciiMaster(wrapper);//ASCII 协议
		ModbusMaster master = getInstance().createTcpMaster(params, false);// TCP
																			// 协议
		master.init();

		return master;
	}

	public ModbusFactory getInstance() {
		if (modbusFactory == null) {
			modbusFactory = new ModbusFactory();
		}
		return modbusFactory;
	}
}
